import { login, getInfo, getVerify } from '@/api/user'
import { setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: localStorage.token || '',
    user: localStorage.user ? JSON.parse(localStorage.user) : {},
    roles: localStorage.roles ? JSON.parse(localStorage.roles) : []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    state.token = ''
    state.user = {}
    state.roles = []
    state.currentTerm = {}
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    localStorage.removeItem('roles')
  },
  SET_TOKEN: (state, token) => {
    state.token = token
    window.localStorage.setItem('token', token)
  },
  SET_USER: (state, user) => {
    state.user = user
    window.localStorage.setItem('user', JSON.stringify(user))
  },
  SET_ROLE: (state, roles) => {
    state.roles = roles
    window.localStorage.setItem('roles', JSON.stringify(roles))
  }
}

const actions = {
  // user login
  login({ dispatch, commit }, params) {
    return new Promise((resolve, reject) => {
      login(params).then(token => {
        if (token && typeof token === 'string') {
          commit('SET_TOKEN', token)
          setToken(token)
          dispatch('getInfo').then(() => {
            resolve(token)
          })
        } else {
          resolve(token)
        }
      }).catch((res) => {
        reject(res)
      })
    })
  },

  getVerify({ commit, state }, params) {
    return new Promise((resolve, reject) => {
      getVerify(params).then(response => {
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(res => {
        if (res) {
          commit('SET_USER', res)
          commit('SET_ROLE', res.userRoles)
        }
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

